package com.gljr.autotest.tool;

import org.openqa.selenium.Alert;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

/**
 * @author frog
 * @version 1.0
 */
public class PopUpAlerts {
	/**
	 * @param driver
	 * @param acceptNextAlert
	 */
	public void handleAlert(WebDriver driver, boolean acceptNextAlert) {

		if (this.isAlertPresent(driver)) {
			(new WebDriverWait(driver, 10)).until(ExpectedConditions.alertIsPresent());
			this.closeAlertAndGetItsText(driver, acceptNextAlert);
		}
	}

	/**
	 * @param driver
	 * @param acceptNextAlert
	 * @return String
	 */
	private String closeAlertAndGetItsText(WebDriver driver, boolean acceptNextAlert) {
		try {
			Alert alert = driver.switchTo().alert();
			String alertText = alert.getText();
			if (acceptNextAlert) {
				alert.accept();
			} else {
				alert.dismiss();
			}
			System.out.println(alertText);
			return alertText;
		} finally {
			acceptNextAlert = true;
		}
	}

	/**
	 * @param driver
	 * @return boolean
	 */
	private boolean isAlertPresent(WebDriver driver) {
		try {
			driver.switchTo().alert();
			return true;
		} catch (NoAlertPresentException e) {
			return false;
		}
	}
}
